package com.cskaoyan.market.config;

import com.cskaoyan.market.shiro.AdminRealm;
import com.cskaoyan.market.shiro.MarketAuthenticator;
import com.cskaoyan.market.shiro.WxRealm;
import org.apache.shiro.authc.Authenticator;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ShiroConfig
 * @Description
 * @Author MZ
 * @Date 2023/5/25 8:54
 */
@Configuration
public class ShiroConfig {

    //向spring容器中注册一个认证器，需要关联realm
    @Bean
    public Authenticator authenticator(AdminRealm adminRealm, WxRealm wxRealm){
        MarketAuthenticator authenticator = new MarketAuthenticator();
        List<Realm> realmList = new ArrayList<>();
        realmList.add(adminRealm);
        realmList.add(wxRealm);
        authenticator.setRealms(realmList);
        return authenticator;
    }

    @Bean
    public SecurityManager securityManager(SessionManager sessionManager, Authenticator authenticator, AdminRealm adminRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setSessionManager(sessionManager);
        //给授权使用的realm，只有后台管理系统才需要授权
        securityManager.setRealm(adminRealm);
        securityManager.setAuthenticator(authenticator);
        return securityManager;
    }

    //还需要shiroFilter---基于web进行认证、授权都需要使用filter
    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);
        return factoryBean;
    }
    //需要进行注解式鉴权，还需要导入一个类
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }

}
